package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.cache.service.IUserInfoCacheService;
import cn.wolfcode.luowowo.cache.service.IVerifyCodeCacheService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.common.util.Consts;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import com.alibaba.fastjson.JSON;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

@RestController
public class LoginController {
    @Reference
    private IUserInfoService userInfoService;
    @Reference
    private IVerifyCodeCacheService verifyCodeCacheService;
    @Reference
    private IUserInfoCacheService userInfoCacheService;

    @RequestMapping("/checkPhone")
    private Boolean checkPhone(String phone) {
        return userInfoService.checkPhone(phone);
    }

    @RequestMapping("/userRegist")
    private Object userRegist(String nickname, String password, String rpassword, String verifyCode, String phone) {
        return userInfoService.userRegist(nickname, password, rpassword, verifyCode, phone);
    }

    @RequestMapping("/sendVerifyCode")
    private Object sendVerifyCode(String phone) {
        AjaxResult result = new AjaxResult();
        if (verifyCodeCacheService.getVerifyCode(phone) != null) {
            return result.mark("验证码已发送,请稍后再试");
        }
        //发送验证码
        String verifyCode = UUID.randomUUID().toString().substring(0, 4);
        verifyCodeCacheService.setVerifyCode(phone,verifyCode);
        //模拟短信
        System.out.println("验证码: " + verifyCode);
        return result;
    }

    @RequestMapping("/userLogin")
    private Object userLogin(String phone, String password, HttpSession session, HttpServletResponse resp) {
        AjaxResult result = userInfoService.userLogin(phone, password);
        //判断当前操作是否登录成功,把登录成功的对象存入session和redis
        if (result.isSuccess()) {
            //把当前登录对象存入session
            Object userInfo = result.getData();
            session.setAttribute(Consts.USER_INFO,userInfo);

            //把登录成功的对象转成JSON,存入redis
            String token = UUID.randomUUID().toString().replaceAll("-", "");
            userInfoCacheService.setUserInfo(token, JSON.toJSONString(userInfo));

            //把token以cookie方式返回给客户端
            Cookie cookie = new Cookie(Consts.USER_INFO_TOKEN, token);
            //设置访问路径,"/"为所有路径都有效
            cookie.setPath("/");
            resp.addCookie(cookie);
        }
        return result;
    }
}
